import React, {useState} from 'react';
import {ActivityIndicator, Alert, FlatList, Modal, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {useFocusEffect, useNavigation} from '@react-navigation/native';
import {Ionicons} from '@expo/vector-icons';
import AppHeader from '../components/AppHeader';
import GradientButton from '../components/GradientButton';
import { Colors } from '../constants/colors';
import InputField from '../components/InputField';
import DateField from '../components/DateField';
import DateTimeField from '../components/DateTimeField';
import {bodyDataService, exerciseService} from '../services';
import {UserBodyDataVo, UserExerciseVo} from '../types/api';


export default function ExerciseRecordsScreen() {
	const navigation = useNavigation();
	const [exercises, setExercises] = useState<UserExerciseVo[]>([]);
	const [bodyData, setBodyData] = useState<UserBodyDataVo | null>(null);
	const [showAddModal, setShowAddModal] = useState(false);
	const [loading, setLoading] = useState(true);
	const [saving, setSaving] = useState(false);
	const [formData, setFormData] = useState({
		exerciseType: '',
		duration: '',
		dateTime: '', // 改为dateTime，存储完整的日期时间
	});
	const [bodyBirthDate, setBodyBirthDate] = useState('');
	const [bodyHeight, setBodyHeight] = useState('');
	const [bodyWeight, setBodyWeight] = useState('');

	// 加载数据
	const loadData = async () => {
		try {
			setLoading(true);

			// 并行加载身体数据和运动记录
			const [bodyDataResult, exerciseResult] = await Promise.allSettled([
				bodyDataService.getBodyData(),
				exerciseService.getExerciseRecords({pageNum: 1, pageSize: 50})
			]);

			// 处理身体数据
			if (bodyDataResult.status === 'fulfilled') {
				setBodyData(bodyDataResult.value);
				setBodyBirthDate(bodyDataResult.value.birthday || '');
				setBodyHeight(bodyDataResult.value.height?.toString() || '');
				setBodyWeight(bodyDataResult.value.weight?.toString() || '');
			} else {
				console.log('身体数据为空或加载失败');
			}

			// 处理运动记录
			if (exerciseResult.status === 'fulfilled') {
				setExercises(exerciseResult.value.records || []);
			} else {
				console.error('加载运动记录失败:', exerciseResult.reason);
			}
		} catch (error) {
			console.error('加载数据失败:', error);
		} finally {
			setLoading(false);
		}
	};

	// 页面聚焦时重新加载数据
	useFocusEffect(
		React.useCallback(() => {
			loadData();
		}, [])
	);

	const handleAddExercise = async () => {
		if (!formData.exerciseType || !formData.duration || !formData.dateTime) {
			Alert.alert('錯誤', '請填寫必要欄位');
			return;
		}

		try {
			setSaving(true);

			await exerciseService.addExerciseRecord({
				type: formData.exerciseType,
				time: formData.dateTime, // 直接使用已格式化的时间
				duration: parseInt(formData.duration),
			});

			setShowAddModal(false);
			setFormData({exerciseType: '', duration: '', dateTime: ''});
			Alert.alert('成功', '運動記錄添加成功');

			// 重新加载数据
			loadData();
		} catch (error: any) {
			console.error('添加运动记录失败:', error);
			Alert.alert('錯誤', error.message || '添加運動記錄失敗');
		} finally {
			setSaving(false);
		}
	};

	const handleDeleteExercise = (exerciseId: number) => {
		Alert.alert(
			'確認刪除',
			'確定要刪除這條運動記錄嗎？',
			[
				{text: '取消', style: 'cancel'},
				{
					text: '刪除',
					style: 'destructive',
					onPress: async () => {
						try {
							await exerciseService.deleteExerciseRecord(exerciseId);
							Alert.alert('成功', '運動記錄刪除成功');
							loadData(); // 重新加载数据
						} catch (error: any) {
							console.error('刪除運動記錄失敗:', error);
							Alert.alert('錯誤', error.message || '刪除運動記錄失敗');
						}
					}
				}
			]
		);
	};

	// 保存身体数据
	const handleSaveBodyData = async () => {
		try {
			setSaving(true);

			const bodyDataToSave = {
				height: bodyHeight ? parseInt(bodyHeight) : undefined,
				weight: bodyWeight ? parseInt(bodyWeight) : undefined,
				birthday: bodyBirthDate || undefined,
			};

			await bodyDataService.saveOrUpdateBodyData(bodyDataToSave);
			Alert.alert('成功', '身體數據保存成功');

			// 重新加载数据
			loadData();
		} catch (error: any) {
			console.error('保存身体数据失败:', error);
			Alert.alert('錯誤', error.message || '保存身體數據失敗');
		} finally {
			setSaving(false);
		}
	};

	const renderExerciseCard = ({item}: { item: UserExerciseVo }) => (
		<View style={styles.exerciseCard}>
			<View style={styles.exerciseHeader}>
				<View style={styles.exerciseIcon}>
					<Ionicons name="calendar" size={16} color={Colors.gray[400]}/>
				</View>
				<View style={styles.exerciseInfo}>
					<Text style={styles.exerciseDate}>{new Date(item.time).toLocaleString()}</Text>
					<Text style={styles.exerciseType}>{item.type}</Text>
				</View>
				<View style={styles.exerciseActions}>
					<Text style={styles.exerciseDuration}>{item.duration}分鐘</Text>
					<TouchableOpacity
						style={styles.deleteButton}
						onPress={() => handleDeleteExercise(item.id)}
					>
						<Ionicons name="trash" size={16} color={Colors.gray[400]}/>
					</TouchableOpacity>
				</View>
			</View>
		</View>
	);

	if (loading) {
		return (
			<SafeAreaView style={styles.container}>
				<AppHeader title="運動數據記錄" showBack/>
				<View style={styles.loadingContainer}>
					<ActivityIndicator size="large" color={Colors.primary}/>
					<Text style={styles.loadingText}>加載中...</Text>
				</View>
			</SafeAreaView>
		);
	}

	return (
		<SafeAreaView style={styles.container}>
			<AppHeader title="運動數據記錄" showBack/>

			<View style={styles.content}>
				{/* Body Data Section */}
				<View style={styles.section}>
					<View style={styles.sectionHeader}>
						<View style={styles.sectionIndicator}/>
						<Text style={styles.sectionTitle}>身體數據</Text>
					</View>

					<View style={styles.bodyDataForm}>
						<View style={{marginBottom: 12}}>
							<DateField label="出生日期" value={bodyBirthDate} onChange={setBodyBirthDate} variant="card"/>
						</View>
						<View style={styles.formRow}>
							<View style={{flex: 1, marginBottom: 12}}>
								<InputField label="身高 (cm)" value={bodyHeight} onChangeText={setBodyHeight} keyboardType="numeric"
								            variant="card"/>
							</View>
							<View style={{flex: 1, marginBottom: 12}}>
								<InputField label="體重 (kg)" value={bodyWeight} onChangeText={setBodyWeight} keyboardType="numeric"
								            variant="card"/>
							</View>
						</View>
					</View>
				</View>

				{/* Exercise Records Section */}
				<View style={styles.section}>
					<View style={styles.sectionHeader}>
						<View style={styles.sectionIndicator}/>
						<Text style={styles.sectionTitle}>運動記錄</Text>
						<TouchableOpacity onPress={() => setShowAddModal(true)} style={styles.addButton}>
							<Ionicons name="add" size={16} color={Colors.primary}/>
							<Text style={styles.addButtonText}>添加運動</Text>
						</TouchableOpacity>
					</View>

					<FlatList
						data={exercises}
						renderItem={renderExerciseCard}
						keyExtractor={(item) => item.id.toString()}
						style={styles.exercisesList}
						showsVerticalScrollIndicator={false}
					/>
				</View>

				<GradientButton
					title={saving ? "保存中..." : "保存數據"}
					onPress={handleSaveBodyData}
					disabled={saving}
					style={styles.saveButton}
				/>
			</View>

			{/* Add Exercise Modal */}
			<Modal
				visible={showAddModal}
				transparent
				animationType="slide"
				onRequestClose={() => setShowAddModal(false)}
			>
				<View style={styles.modalOverlay}>
					<View style={styles.modalContent}>
						<Text style={styles.modalTitle}>添加運動</Text>

						<View style={styles.modalForm}>
							<View style={{marginBottom: 12}}>
								<InputField label="運動內容" value={formData.exerciseType}
								            onChangeText={(text) => setFormData({...formData, exerciseType: text})} variant="card"/>
							</View>

							<View style={{marginBottom: 12}}>
                                <InputField 
                                    label={"運動時長\n(分鐘)"}
                                    value={formData.duration}
                                    onChangeText={(text) => setFormData({...formData, duration: text})} 
                                    keyboardType="numeric"
                                    variant="card"/>
							</View>

							<View style={{marginBottom: 12}}>
								<DateTimeField
									label="運動日期時間"
									value={formData.dateTime}
									onChange={(text) => setFormData({...formData, dateTime: text})}
									variant="card"
									mode="datetime"
								/>
							</View>
						</View>

						<View style={styles.modalActions}>
							<TouchableOpacity
								style={[styles.modalButton, styles.cancelButton]}
								onPress={() => setShowAddModal(false)}
							>
								<Text style={styles.cancelButtonText}>取消</Text>
							</TouchableOpacity>
							<GradientButton
								title={saving ? "添加中..." : "立即添加"}
								onPress={handleAddExercise}
								disabled={saving}
								style={styles.confirmButton}
							/>
						</View>
					</View>
				</View>
			</Modal>
		</SafeAreaView>
	);
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: Colors.white,
	},
	loadingContainer: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
	},
	loadingText: {
		marginTop: 16,
		fontSize: 16,
		color: Colors.gray[600],
	},
	content: {
		flex: 1,
		padding: 16,
	},
	section: {
		marginBottom: 24,
	},
	sectionHeader: {
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 16,
	},
	sectionIndicator: {
		width: 4,
		height: 24,
		backgroundColor: Colors.primary,
		borderRadius: 2,
		marginRight: 12,
	},
	sectionTitle: {
		fontSize: 18,
		fontWeight: '600',
		color: Colors.gray[800],
		flex: 1,
	},
	addButton: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	addButtonText: {
		color: Colors.primary,
		fontSize: 14,
		fontWeight: '600',
		marginLeft: 4,
	},
	bodyDataForm: {
		backgroundColor: Colors.gray[100],
		borderRadius: 12,
		padding: 16,
	},
	formRow: {
		flexDirection: 'row',
		gap: 12,
	},
	formGroup: {
		flex: 1,
		marginBottom: 16,
	},
	inputLabel: {
		fontSize: 14,
		color: Colors.gray[600],
		marginBottom: 8,
	},
	input: {
		borderWidth: 1,
		borderColor: Colors.gray[300],
		borderRadius: 8,
		paddingHorizontal: 12,
		paddingVertical: 8,
		fontSize: 14,
		backgroundColor: Colors.white,
	},
	exercisesList: {
		maxHeight: 300,
	},
	exerciseCard: {
		backgroundColor: Colors.white,
		borderRadius: 12,
		marginBottom: 8,
		elevation: 2,
		shadowColor: Colors.black,
		shadowOffset: {
			width: 0,
			height: 1,
		},
		shadowOpacity: 0.1,
		shadowRadius: 4,
	},
	exerciseHeader: {
		flexDirection: 'row',
		alignItems: 'center',
		padding: 12,
	},
	exerciseIcon: {
		width: 32,
		height: 32,
		backgroundColor: Colors.gray[100],
		borderRadius: 16,
		alignItems: 'center',
		justifyContent: 'center',
		marginRight: 12,
	},
	exerciseInfo: {
		flex: 1,
	},
	exerciseDate: {
		fontSize: 12,
		color: Colors.gray[600],
		marginBottom: 2,
	},
	exerciseType: {
		fontSize: 16,
		fontWeight: '600',
		color: Colors.gray[800],
	},
	exerciseActions: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	exerciseDuration: {
		fontSize: 14,
		fontWeight: '600',
		color: Colors.primary,
		marginRight: 12,
	},
	deleteButton: {
		width: 32,
		height: 32,
		backgroundColor: Colors.gray[100],
		borderRadius: 16,
		alignItems: 'center',
		justifyContent: 'center',
	},
	saveButton: {
		marginTop: 24,
	},
	modalOverlay: {
		flex: 1,
		backgroundColor: 'rgba(0, 0, 0, 0.5)',
		justifyContent: 'center',
		alignItems: 'center',
	},
	modalContent: {
		width: '86%',
		backgroundColor: Colors.white,
		borderRadius: 16,
		padding: 20,
	},
	modalTitle: {
		fontSize: 18,
		fontWeight: '600',
		color: Colors.gray[800],
		textAlign: 'center',
		marginBottom: 24,
	},
	modalForm: {
		marginBottom: 24,
	},
	modalInputWrap: {
		backgroundColor: Colors.gray[100],
		borderRadius: 12,
		borderWidth: 1,
		borderColor: Colors.gray[200],
		paddingHorizontal: 14,
		paddingVertical: 10,
	},
	modalInput: {
		height: 24,
		color: Colors.black,
	},
	modalActions: {
		flexDirection: 'row',
		gap: 12,
		marginTop: 4,
	},
	modalButton: {flex: 1},
	cancelButton: {
		minHeight: 48, // 与GradientButton保持一致的高度
		backgroundColor: Colors.gray[200],
		borderRadius: 12,
		alignItems: 'center',
		justifyContent: 'center',
	},
	cancelButtonText: {
		fontSize: 16,
		color: Colors.gray[600],
		fontWeight: '500',
	},
	confirmButton: {flex: 1},
});
